import json
from pathlib import Path


class JsonHandler:

    def __init__(self, file_path):
        self.file_path = Path.cwd() / file_path
        self.data = self.read() or {}

    def read(self):
        try:
            with self.file_path.open("r", encoding="utf-8") as f:
                return json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            return None

    def write(self):
        if not self.data:
            raise ValueError("No data to write. Please update the data first.")
        with self.file_path.open("w", encoding="utf-8") as f:
            json.dump(self.data, f, indent=4, ensure_ascii=False)

    def update(self, new_data):
        self.data.update(new_data)
        self.write()

    def __str__(self):
        return json.dumps(self.data, indent=4)

    def __getitem__(self, key):
        return self.data.get(key)

    def __setitem__(self, key, value):
        self.data[key] = value
        self.write()

    def __delitem__(self, key):
        if key in self.data:
            del self.data[key]
            self.write()


if __name__ == "__main__":
    json_file_path = "Res/Setting.json"
    handler = JsonHandler(json_file_path)
    print("读取的数据:", handler.data)

    # 更新数据
    new_entry = {"year": [1998, 2025], "month": [3, 6, 9, 12]}
    handler.update(new_entry)
    print("读取的数据:", handler.data)

    # 获取特定键的值
    print("获取 year 的值:", handler["year"])

    # 设置新的键值对
    handler["day"] = [1, 15]
    print("设置 day 后的数据:", handler.data)

    # 删除键值对
    del handler["month"]
    print("删除 month 后的数据:", handler.data)
    # 打印整个 YAML 内容
    print("整个 JSON 内容:\n", str(handler))
